package com.yjc.drygoods.search.servcie.impl;

import com.alibaba.fastjson.JSON;
import com.yjc.common.constant.EsConstant;
import com.yjc.common.to.PurchaseDetailTo;
import com.yjc.common.to.SkuEsModel;
import com.yjc.common.to.SkuInfoTo;
import com.yjc.drygoods.search.config.DryGoodsElasticSearchConfig;
import com.yjc.drygoods.search.servcie.ElasticSearchServcie;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yjc
 * @create 2022-09-07 15:58
 */
@Slf4j
@Service
public class ElasticSearchServcieImpl implements ElasticSearchServcie {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean saveSkuEsModels(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId() + "");
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, DryGoodsElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        BulkItemResponse[] items = bulk.getItems();
        List<String> collect = Arrays.stream(items).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架成功：{}", collect);
        return b;
    }


    @Override
    public void downAllSku(List<Long> skuIds) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (Long skuId : skuIds) {
            DeleteRequest deleteRequest = new DeleteRequest(EsConstant.PRODUCT_INDEX);
            deleteRequest.id(skuId.toString());
            bulkRequest.add(deleteRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, DryGoodsElasticSearchConfig.COMMON_OPTIONS);


    }

    @Override
    public void saveOldYearPurchaseDetail(List<PurchaseDetailTo> purchaseDetailTos) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (PurchaseDetailTo purchaseDetail : purchaseDetailTos) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PURCHASEDETAIL_INDEX);
            indexRequest.id(purchaseDetail.getId() + "");
            String s = JSON.toJSONString(purchaseDetail);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, DryGoodsElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        BulkItemResponse[] items = bulk.getItems();
        List<String> collect = Arrays.stream(items).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("干货采购需求录入成功：{}", collect);
    }


    @Override
    public void updateEsSaleCount(List<SkuInfoTo> skuInfos) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuInfoTo skuInfo : skuInfos) {
            Long skuId = skuInfo.getSkuId();
            Long saleCount = skuInfo.getSaleCount();
            Double weight = skuInfo.getWeight();
            UpdateRequest updateRequest = new UpdateRequest(EsConstant.PRODUCT_INDEX, skuId.toString());

            String source_str = "ctx._source.saleCount += params.saleCount";
            HashMap<String, Object> params = new HashMap<>();
            params.put("saleCount", saleCount * weight);
            Script script = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, source_str, params);
            updateRequest = updateRequest.script(script);
            bulkRequest.add(updateRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, DryGoodsElasticSearchConfig.COMMON_OPTIONS);
    }

    @Override
    public void updateSkuPrice(List<SkuInfoTo> skuInfos) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuInfoTo skuInfo : skuInfos) {
            Long skuId = skuInfo.getSkuId();
            BigDecimal reducedPrice = skuInfo.getReducedPrice();
            UpdateRequest updateRequest = new UpdateRequest(EsConstant.PRODUCT_INDEX, skuId.toString());

            String source_str = "ctx._source.skuPrice = params.skuPrice";
            HashMap<String, Object> params = new HashMap<>();
            params.put("skuPrice", reducedPrice);
            Script script = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, source_str, params);
            updateRequest = updateRequest.script(script);
            bulkRequest.add(updateRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, DryGoodsElasticSearchConfig.COMMON_OPTIONS);

    }


}
